package com.yl.nettylearning.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author yangl
 */
public class NewIOClient {
    /**
     * 只拷贝，没输出
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(7001));
        String filename = "jvm-master.zip";
        FileChannel fileChannel = new FileInputStream(filename).getChannel();
        long startTime = System.currentTimeMillis();
        //在linux下，一个transferTo方法就可以完成
        //在windows下，一次调用transferTo只能发送8m，就需要 分段传输文件，而且更主要的是传输的位置
        long transferCount = 0;
        System.out.println(fileChannel.size());
        double ceil = (fileChannel.size()) / (8.0 * 1024 * 1024);
        System.out.println(ceil);
        if(fileChannel.size()  < (8.0 * 1024 * 1024)){
            transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
        }else{
            int page = (int) Math.ceil(fileChannel.size() / (8.0 * 1024 * 1024));
            int i = 0;
            while (i < page){
                transferCount = fileChannel.transferTo(i * 8 * 1024 * 1024, 8 * 1024 * 1024, socketChannel);
                transferCount += i * 8 * 1024 * 1024;
                i++;
            }
        }
        System.out.println("发送的字节数 = " + transferCount + "耗时：" + (System.currentTimeMillis() - startTime));
        fileChannel.close();
    }
}
